﻿using Common;
using DevExpress.XtraEditors;
using DLL;
using SQLDLL;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NursingDocumentInfoSystem
{
    public partial class PatientOrders : Form
    {
        public string Pid = "";
        public string Vid = "";
        public string Did = "";
        public string[] name_tj;
        public ArrayList NameList = new ArrayList();
        public ArrayList NumList = new ArrayList();
        public ArrayList WayList = new ArrayList();
        public PatientOrders(string PatientID, string VisitID, string DepartmentCode)
        {
            InitializeComponent();
            Pid = PatientID.Trim();
            Vid = VisitID;
            Did = DepartmentCode;
            string sql = "select  [Name]+'&'+ Code  as NameAndCode from C_LocalDropSource(NOLOCK) where ','+NurseCellCodes+',' like '%," + Did + ",%' order by Sort";
            cbbTj.Properties.Items.Add("全部");
            DataSet yizhutj = SqlHelper.ExecuteDataset(sql, CommandType.Text);

            if (yizhutj != null && yizhutj.Tables.Count > 0 && yizhutj.Tables[0].Rows.Count > 0)
            {
                name_tj = new string[yizhutj.Tables[0].Rows.Count];
                for (int i = 0; i < yizhutj.Tables[0].Rows.Count; i++)
                {
                    name_tj[i] = yizhutj.Tables[0].Rows[i][0].ToString();
                    cbbTj.Properties.Items.Add(name_tj[i].Split('&')[0]);
                }
            }
            simpleButton1_Click(null, null);
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string Starttime = dateEdit1.Text+ "" ;
            string Tj = cbbTj.Text;
            string zl = cbbTypes.Text;
            string sql = "select *   from V_YDHL_ORDERS where PATIENT_ID = '" + Pid + "' and VISIT_ID = '" + Vid + "'";
            if (!string.IsNullOrEmpty(Tj) && Tj != "全部")
            {
                string tempselect = @"SELECT      [Code]    FROM [BNNursingDocsSystem_Develop].[dbo].[C_LocalDropSource](NOLOCK) where Name ='" + Tj + "' and NurseCellCodes like '%" + Did + "%'";
                string tempcode = SqlHelper.ExecuteScalar(CommandType.Text, tempselect).ToString();
                tempselect = @"SELECT     [InterfaceCode]   FROM [BNNursingDocsSystem_Develop].[dbo].[C_DropSourceRelationship](NOLOCK) where LocalCode ='" + tempcode + "'";
                DataTable intercode = SqlHelper.ExecuteDataset(tempselect, CommandType.Text).Tables[0];
                tempselect = @"SELECT    [Name]  FROM [BNNursingDocsSystem_Develop].[dbo].[C_InterfaceDropSource](NOLOCK) where Code = '" + intercode.Rows[0][0].ToString() + "'";
                string methodname = SqlHelper.ExecuteScalar(CommandType.Text, tempselect).ToString();
                sql += "and (METHOD = '" + methodname + "'   ";
                for (int i = 1; i < intercode.Rows.Count; i++)
                {

                    tempselect = @"SELECT    [Name]  FROM [BNNursingDocsSystem_Develop].[dbo].[C_InterfaceDropSource](NOLOCK) where Code = '" + intercode.Rows[i][0].ToString() + "'";
                    if (SqlHelper.ExecuteScalar(CommandType.Text, tempselect) == null) continue;
                    else
                    {
                        methodname = SqlHelper.ExecuteScalar(CommandType.Text, tempselect).ToString();
                        sql += "or  METHOD = '" + methodname + "' ";
                    }

                }
                sql += ")";
                //Tj = name_tj.Where(m => m+ "" .Split('&')[0] == Tj).ToList()[0].ToString().Split('&')[0].ToString();
            }


            //EFFECT_FLAG:
            //050：编辑中
            //060：新增医嘱未确认
            //070：新增医嘱已确认
            //080：医嘱撤销
            //085：已确认撤销
            //090：已确认执行
            //100: 停止医嘱未确认
            //110：停止医嘱已确认
            //120、130是作废未确认已确认，但库里没有数据



            switch (zl)
            {
                case "当前":
                    sql += "  and VALID_FLAG='有效' and EFFECT_FLAG  in ('090','060','070') ";
                    break;
                case "停止":
                    sql += " and VALID_FLAG='有效' and EFFECT_FLAG  in ('100','110') ";
                    break;
                case "长期":
                    sql += " and REPEAT_SIGNAL='CZ'  and EFFECT_FLAG  in ('060','070','080','085','090','100','110') ";
                    break;
                case "临时":
                    sql += " and REPEAT_SIGNAL='LZ'  and EFFECT_FLAG in ('060','070','080','085','090','100','110') ";
                    break;
                case "当前长期":
                    sql += " and REPEAT_SIGNAL='CZ' and EFFECT_FLAG  in ('090')  ";
                    break;
                case "当前临时":
                    sql += " and REPEAT_SIGNAL='LZ' and EFFECT_FLAG  in ('090')  ";
                    break;
                case "检查检验":
                    sql += " and ( TYPE_CODE = 'JY'  or TYPE_CODE = 'JC') ";
                    break;
                case "全部":
                    sql += "  ";
                    break;
                default:
                    sql += "   and VALID_FLAG='有效' and EFFECT_FLAG  in ('090','060','070')  ";
                    break;
            }
            if (!string.IsNullOrEmpty(Starttime))
            {
                string date = dateEdit1.Text + " 00:00:00";

                sql += @"and START_TIME >to_date('" + date + "','yyyy/mm/dd hh24:mi:ss') ";


            }
            if (checkBox1.Checked == true)
            {
                sql += @"and  MEDICINE_TYPE = '是' ";
            }

            //if (!string.IsNullOrEmpty(Tj) && Tj != "全部")
            //{
            //    //  select += @" and method in (select distinct yz.Method  from Orders yz
            //    // left join  C_InterfaceDropSource m on yz.METHOD = m.Name
            //    //left join  C_DropSourceRelationship r on  r.InterfaceCode = m.Code
            //    //left join C_LocalDropSource t on t.Code = r.LocalCode where t.Name='" + Tj + "'  and ','+ t.NurseCellCodes +',' like '%," + CurRow["NURSE_CELL_CODE"] + ",%' )";

            // //   select += @"and Method = '" + cbbTj.Text + @"'";
            //}

            //   select += @"order by CombNo";
            //   DataSet order = SqlHelper.ExecuteDataset(select, CommandType.Text);
            //   DataTable search = order.Tables[0];

            //     WebReference.BNNursingDocsSystem web1 = new WebReference.BNNursingDocsSystem();
            
            DataTable order = OracleHelper.ExecToSqlGetTable(sql, SQLDLL.Base.HTConnStr.ToString());
            //web1.GetOrdersList(patientid, VisitID, null, "0812", Starttime, Tj, zl).D;
            order.Columns.Add("勾选", System.Type.GetType("System.Boolean"));
            order.Columns["勾选"].SetOrdinal(0);
            order.Columns["START_TIME"].SetOrdinal(1);
            order.Columns["ORDER_START_DOC"].SetOrdinal(2);
            order.Columns.Add("组标", typeof(string));
            order.Columns.Add("自备", typeof(string));
            order.Columns.Add("出院带药", typeof(string));
            order.Columns["组标"].SetOrdinal(3);
            order.Columns["ORDER_TEXT"].SetOrdinal(4);
            order.Columns["SPEC"].SetOrdinal(5);
            order.Columns["DOSE"].SetOrdinal(6);
            order.Columns["DOSE_UNIT"].SetOrdinal(7);
            order.Columns["FREQUENCY_CODE"].SetOrdinal(8);
            order.Columns["REMARKS"].SetOrdinal(9);
            order.Columns["END_TIME"].SetOrdinal(10);
            order.Columns["TYPE_CODE"].SetOrdinal(11);
            order.Columns["METHOD"].SetOrdinal(12);
            order.Columns["自备"].SetOrdinal(13);
            order.Columns["出院带药"].SetOrdinal(14);
            order.Columns["SKINTEST_RESULT"].SetOrdinal(15);


            gridControl1.DataSource = UpdateDataTable(order);


            //    gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsCustomization.AllowSort = false;

            gridView1.Columns["INTENDING_STOP_TIME"].Visible = false;
            gridView1.Columns["ORDER_CODE"].Visible = false;
            gridView1.Columns["ORDER_ID"].Visible = false;
            gridView1.Columns["ORDER_START_DOC"].Visible = false;
            gridView1.Columns["ORDER_START_DOC_ID"].Visible = false;
            gridView1.Columns["ORDER_START_NURSE"].Visible = false;
            gridView1.Columns["ORDER_START_NURSE_ID"].Visible = false;
            gridView1.Columns["ORDER_END_DOC"].Visible = false;
            gridView1.Columns["ORDER_END_DOC_ID"].Visible = false;
            gridView1.Columns["ORDER_END_NURSE"].Visible = false;
            gridView1.Columns["ORDER_END_NURSE_ID"].Visible = false;

            gridView1.Columns["REPEAT_SIGNAL"].Visible = false;
            gridView1.Columns["DEPT_CODE"].Visible = false;
            gridView1.Columns["DEPT_NAME"].Visible = false;
            gridView1.Columns["WARD_CODE"].Visible = false;
            gridView1.Columns["WARD_NAME"].Visible = false;
            gridView1.Columns["PATIENT_ID"].Visible = false;
            gridView1.Columns["BED_NO"].Visible = false;
            gridView1.Columns["VISIT_ID"].Visible = false;
            gridView1.Columns["INFANT_PID"].Visible = false;
            gridView1.Columns["DEPT_CODE"].Visible = false;
            gridView1.Columns["DEPT_NAME"].Visible = false;
            gridView1.Columns["PATIENT_NAME"].Visible = false;
            gridView1.Columns["IN_STATUS"].Visible = false;
            gridView1.Columns["MR_STATUS"].Visible = false;
            gridView1.Columns["MEDICINE_TYPE"].Visible = false;
            gridView1.Columns["REMARKS"].Caption = "医生说明";
            gridView1.Columns["SPEED"].Visible = false;
            gridView1.Columns["DOSAGE"].Visible = false;
            gridView1.Columns["HIGHRISK"].Visible = false;
            gridView1.Columns["SKINTEST_RESULT"].Caption = "皮试结果";
            gridView1.Columns["ORDER_STATUS"].Visible = false;
            gridView1.Columns["VALID_FLAG"].Visible = false;
            gridView1.Columns["EFFECT_FLAG"].Visible = false;
            gridView1.Columns["CHILD_ID"].Visible = false;
            gridView1.Columns["IS_SUB_ORDER"].Visible = false;

            gridView1.Columns["START_TIME"].Caption = "开出时间";
            gridView1.Columns["END_TIME"].Caption = "停止时间";
            gridView1.Columns["ORDER_TEXT"].Caption = "医嘱";
            gridView1.Columns["FREQUENCY_CODE"].Caption = "频次";
            gridView1.Columns["SPEC"].Caption = "规格";
            gridView1.Columns["METHOD"].Caption = "用法";
            gridView1.Columns["DOSE"].Caption = "剂量";
            gridView1.Columns["DOSE_UNIT"].Caption = "剂量单位";
            gridView1.Columns["TYPE_CODE"].Caption = "类型";
            gridView1.Columns["METHOD"].Caption = "用法";
            gridView1.Columns["DOSE"].Caption = "剂量";
            gridView1.Columns["DOSE_UNIT"].Caption = "剂量单位";
            gridView1.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;   //是否显示过滤面板
            gridView1.OptionsCustomization.AllowFilter = false;                      //是否允许过滤
            gridView1.Appearance.Row.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridView1.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridView1.OptionsMenu.EnableColumnMenu = false;
            gridView1.OptionsView.ShowGroupPanel = false;
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.RowSelect;
            for (int i = 1; i < gridView1.DataRowCount; i++)
            {
                if (gridView1.GetDataRow(i)["ORDER_ID"].ToString() == gridView1.GetDataRow(i - 1)["ORDER_ID"].ToString())
                {
                    gridView1.SetRowCellValue(i, gridView1.Columns["START_TIME"], null);
                    gridView1.SetRowCellValue(i, gridView1.Columns["END_TIME"], null);
                    gridView1.SetRowCellValue(i - 1, gridView1.Columns["组标"], "┌");
                    gridView1.SetRowCellValue(i, gridView1.Columns["组标"], "└");
                }

            }
            for (int i = 1; i < gridView1.DataRowCount; i++)
            {
                if (gridView1.GetDataRow(i)["START_TIME"].ToString() == "" && gridView1.GetDataRow(i)["组标"].ToString() == "┌")
                {
                    gridView1.SetRowCellValue(i, gridView1.Columns["组标"], "");
                }

            }
            for (int i = 0; i < gridView1.DataRowCount; i++)
            {

                if ("出院带药" == gridView1.GetDataRow(i)["METHOD"].ToString())
                {
                    gridView1.SetRowCellValue(i, gridView1.Columns["出院带药"], "是");
                }
                else gridView1.SetRowCellValue(i, gridView1.Columns["出院带药"], "否");
                //  gridView1.SetRowCellValue(i, gridView1.Columns["ORDER_TEXT"], gridView1.GetDataRow(i)["ORDER_TEXT"].ToString() + gridView1.GetDataRow(i)["SPEC"].ToString() + gridView1.GetDataRow(i)["DOSE"].ToString() + gridView1.GetDataRow(i)["DOSE_UNIT"].ToString() + gridView1.GetDataRow(i)["METHOD"].ToString() + gridView1.GetDataRow(i)["FREQUENCY_CODE"].ToString());

                if (gridView1.Columns["ORDER_TEXT"].ToString().IndexOf("自备") > -1)
                {
                    gridView1.SetRowCellValue(i, gridView1.Columns["自备"], "是");
                }
                else gridView1.SetRowCellValue(i, gridView1.Columns["自备"], "否");
            }

            for (int i = 1; i < gridView1.DataRowCount; i++)
            {
                if (gridView1.GetDataRow(i)["组标"].ToString() == gridView1.GetDataRow(i - 1)["组标"].ToString())
                {
                    gridView1.SetRowCellValue(i, gridView1.Columns["组标"], "");
                }

            }
            gridView1.RowStyle += GridView1_RowStyle;
            gridView1.RowCellStyle += GridView1_RowCellStyle;
            gridView1.MouseDown += GridView1_MouseDown;
            gridView1.OptionsView.ColumnAutoWidth = false;
            gridView1.Columns["START_TIME"].Width = 150;
            gridView1.Columns["组标"].Width = 40;
            gridView1.Columns["ORDER_TEXT"].Width = 200;
            gridView1.Columns["SPEC"].Width = 75;
            gridView1.Columns["DOSE"].Width = 75;
            gridView1.Columns["DOSE_UNIT"].Width = 75;
            gridView1.Columns["FREQUENCY_CODE"].Width = 75;
            gridView1.Columns["REMARKS"].Width = 150;
            gridView1.Columns["END_TIME"].Width = 150;
            gridView1.Columns["METHOD"].Width = 75;
            gridView1.Columns["自备"].Width = 75;
            gridView1.Columns["勾选"].Width = 30;
            gridView1.Columns["勾选"].Caption = " ";

            for (int i = 0; i < gridView1.Columns.Count; i++)
            {
                if (gridView1.Columns[i].Name != "col勾选")
                {
                    gridView1.Columns[i].OptionsColumn.AllowEdit = false;
                }

            }
        }

        private void GridView1_MouseDown(object sender, MouseEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hInfo = gridView1.CalcHitInfo(new Point(e.X, e.Y));

            if (e.Button == MouseButtons.Left && e.Clicks == 2)
            {
                if (hInfo.InRow)//判断光标是否在行范围内 
                {

                    string value = gridView1.GetDataRow(hInfo.RowHandle)[hInfo.Column.AbsoluteIndex].ToString();
                    Clipboard.SetDataObject(value);

                }
            }
        }

        private void GridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "组标" && e.CellValue.ToString() == "┌" || e.CellValue.ToString() == "└")
            {
                e.Appearance.ForeColor = Color.Red;
            }
        }

        private void GridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            try
            {
                int hand = e.RowHandle;
                if (hand < 0) return;
                DataRow dr = gridView1.GetDataRow(hand);
                if (dr == null) return;

                if (dr["EFFECT_FLAG"]+ ""  == "060") //新增医嘱未确认
                {
                    e.Appearance.ForeColor = Color.Blue;// 改变行字体颜色  
                    e.Appearance.BorderColor = Color.Blue;
                }
                if (dr["EFFECT_FLAG"]+ ""  == "070") //新增医嘱已确认
                {
                    e.Appearance.ForeColor = Color.Orange;// 改变行字体颜色  
                    e.Appearance.BorderColor = Color.Orange;
                }
                if (dr["EFFECT_FLAG"]+ ""  == "100") //停止医嘱未确认
                {
                    e.Appearance.ForeColor = Color.Pink;// 改变行字体颜色  
                    e.Appearance.BorderColor = Color.Pink;
                }
                if (dr["EFFECT_FLAG"]+ ""  == "110") //停止医嘱未确认
                {
                    e.Appearance.ForeColor = Color.Red;// 改变行字体颜色  
                    e.Appearance.BorderColor = Color.Red;
                }
                if (dr["EFFECT_FLAG"]+ ""  == "090") //已执行
                {
                    e.Appearance.ForeColor = Color.Green;// 改变行字体颜色  
                    e.Appearance.BorderColor = Color.Green;
                }

                if (dr["EFFECT_FLAG"]+ ""  == "080" || dr["EFFECT_FLAG"]+ ""  == "085") //已撤销
                {
                    e.Appearance.ForeColor = Color.Gray;// 改变行字体颜色  
                    e.Appearance.BorderColor = Color.Gray;
                }
            }
            catch (Exception) { }
        }
        #region 修改datatable的datatype，让其可以显示完整时间

        /// <summary>
        ///当DataTable中有值时，是不允许修改列的DataType
        /// 修改数据表DataTable某一列的数据类型和记录值
        /// </summary>
        /// <param name="argDataTable">数据表DataTable</param>
        /// <returns>数据表DataTable</returns>
        private DataTable UpdateDataTable(DataTable argDataTable)
        {

            DataTable dtResult = new DataTable(); //克隆表结构
            dtResult = argDataTable.Clone();

            //修改数据列类型

            foreach (DataColumn col in dtResult.Columns)
            {

                if (col.ColumnName == "START_TIME" || col.ColumnName == "END_TIME")
                {
                    col.DataType = typeof(System.String);
                }

            }

            foreach (DataRow row in argDataTable.Rows)
            {
                dtResult.ImportRow(row);
            }

            return dtResult;

        }
        #endregion

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            int num = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {

                if (gridView1.GetDataRow(i)["勾选"].ToString() == "True")
                {
                    num++;
                }
            }
            if(num == 0)
            {
                XtraMessageBox.Show("没有勾选对应输入流体");
            }
            else
            {
               
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    if (gridView1.GetDataRow(i)["勾选"].ToString() == "True")
                    {
                        NameList.Add(gridView1.GetDataRow(i)["ORDER_TEXT"].ToString().Trim());
                        WayList.Add(gridView1.GetDataRow(i)["METHOD"].ToString().Trim());
                        NumList.Add(gridView1.GetDataRow(i)["DOSE"].ToString().Trim());
                    }                    
                }
                DialogResult = DialogResult.Yes;
                Close();
                
            }
        }
    }
}
